package browser

import (
	"ULCrawler/conf"
	"fmt"
	"github.com/tebeka/selenium"
	"github.com/tebeka/selenium/chrome"
)
const (
	seleniumPath = `chromedriver.exe`
)

var port = conf.Conf.DriverPort

var service *selenium.Service

func init() {
	var err error
	opts := make([]selenium.ServiceOption,0)

	service,err=selenium.NewChromeDriverService(seleniumPath, port, opts...)
	if err!=nil {
		panic("启动浏览器驱动服务失败,err= " + err.Error())
	}
}


// 打开一个浏览器
func OpenWebDriver() (selenium.WebDriver,error) {
	//链接本地的浏览器 chrome
	caps := selenium.Capabilities{
		"browserName": "chrome",
	}
	//禁止图片加载，加快渲染速度
	imagCaps := map[string]interface{}{
		//"profile.managed_default_content_settings.images": 2,
	}
	chromeCaps := chrome.Capabilities{
		Prefs: imagCaps,
		Path:  "",
		ExcludeSwitches:[]string{
			"enable-automation",
		},//修改window.navigator.webdriver为undefined 防反爬
		Args: []string{
			//"--headless", // 设置Chrome无头模式，在linux下运行，需要设置这个参数，否则会报错
			//"--no-sandbox",
			"--user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.132 Safari/537.36", // 模拟user-agent，防反爬
		},
	}
	//以上是设置浏览器参数
	caps.AddChrome(chromeCaps)
	return selenium.NewRemote(caps,  fmt.Sprintf("http://localhost:%d/wd/hub", port))
}



func Stop() error {
	return service.Stop()
}